from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
# from rest_framework import serializers
from rest_framework.generics import GenericAPIView

from .utils import OAuthQQ
from rest_framework import status
from .models import OAuthQQUser
from .exceptions import QQAPIException
from .serialisers import QQAuthUserSerializer
# Create your views here.
# url(r'^qq/user/$', views.QQAuthUserView.as_view()),
class QQAuthUserView(GenericAPIView):
    '''用户扫码登录回调处理'''
    serializer_class = QQAuthUserSerializer
    def get(self,request):
        #提取code请求参数
        code = request.query_params.get('code')
        if not code:
            return Response({'message':'缺失code'},status = status.HTTP_400_BAD_REQUEST)
        #创建oath工具对象
        oauth = OAuthQQ()
        try:
            #使用code向QQ服务器发送access_token
            access_token = oauth.get_access_token(code)
            #使用access_token获取用户的openid
            openid = oauth.get_openid(access_token)
            #使用openid查询该扣扣是否绑定美多商城账号
        except QQAPIException :
            return Response({'message':'QQ服务异常'},status=status.HTTP_503_SERVICE_UNAVAILABLE)
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            #如果openid没绑定美多商城用户，创建用户并绑定到openid
            #使用settings的SELEECT_KEY结合itsdangerous模块，对openid进行签名后再响应给前端，为了安全
            access_token_openid = OAuthQQ.generate_save_user_token(openid)
            return Response({'access_token':access_token_openid})

        #如果openid已绑定美多商城用户，直接生成jwt_token，并返回
        else:
            user = oauth_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })

        #如果openid没绑定美多商城用户，创建用户并绑定到openid
    def post(self,request):
        '''绑定用户openid'''
        #获取序列化器
        serializer = self.get_serializer(data = request.data)
        #开启验证
        serializer.is_valid(raise_exception = True)
        #保存校验后的数据
        user = serializer.save()
        #再次生成jwt token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return Response({
            'token':token,
            'user_id':user.id,
            'username':user.username
        })


#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    '''提供QQ登录页面的url'''
    def get(self,request):
        #next 表示从哪个页面进入登录页面，登陆后回到哪个页面
        next = request.query_params.get('next')

        # 创建oauth工具对象
        oauth = OAuthQQ(state=next)

        # 调用获取QQ登录界面的url的工具方法
        login_url = oauth.get_qq_login_url()
        #返回qq登录界面的url给浏览器
        return Response({'login_url':login_url})
